"""
FastAPI 小说爬虫服务
"""
from fastapi import FastAPI, Query, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from typing import Dict, Any

from app_function import fetch_chapter_list, fetch_novel_content, search_results
from config import config
from logger import logger

# 创建 FastAPI 应用实例
app = FastAPI(
    title="小说爬虫API",
    description="支持多网站小说搜索和内容获取的API服务",
    version="1.0.0"
)

# 配置 CORS 中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有域名调用，生产环境建议写具体域名
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法
    allow_headers=["*"],  # 允许所有 headers
)


@app.get("/", tags=["健康检查"])
def health_check() -> Dict[str, str]:
    """
    健康检查接口
    """
    return {"status": "success", "message": "小说爬虫服务运行正常"}


@app.get("/novel/search", tags=["小说搜索"])
def search_novel(keyword: str = Query(..., description="小说关键词", min_length=1)) -> Dict[str, Any]:
    """
    搜索小说接口

    Args:
        keyword: 搜索关键词，至少1个字符

    Returns:
        搜索结果列表，包含标题、作者、URL等信息
    """
    try:
        logger.info(f"API搜索请求: {keyword}")
        results = search_results(keyword)
        return {
            "status": "success",
            "message": f"找到 {len(results)} 个结果",
            "results": results
        }
    except Exception as e:
        logger.error(f"搜索接口错误: {e}")
        raise HTTPException(status_code=500, detail=f"搜索失败: {str(e)}")


@app.get("/novel/chapters", tags=["章节管理"])
def fetch_chapters(url: str = Query(..., description="小说目录页URL")) -> Dict[str, Any]:
    """
    获取小说章节列表接口

    Args:
        url: 小说目录页的完整URL

    Returns:
        章节列表，包含小说标题和所有章节信息
    """
    try:
        logger.info(f"API获取章节列表请求: {url}")
        result = fetch_chapter_list(url)
        chapter_count = len(result.get('chapters', []))
        return {
            "status": "success",
            "message": f"获取到 {chapter_count} 个章节",
            **result
        }
    except Exception as e:
        logger.error(f"获取章节列表接口错误: {e}")
        raise HTTPException(status_code=500, detail=f"获取章节失败: {str(e)}")


@app.get("/novel/content", tags=["内容获取"])
def fetch_content_endpoint(url: str = Query(..., description="小说章节URL")) -> Dict[str, Any]:
    """
    获取小说章节内容接口

    Args:
        url: 小说章节的完整URL

    Returns:
        章节内容，包含章节标题和正文内容
    """
    try:
        logger.info(f"API获取章节内容请求: {url}")
        content = fetch_novel_content(url)
        content_length = len(content.get('content', ''))
        return {
            "status": "success",
            "message": f"内容获取成功，长度: {content_length}",
            "content": content
        }
    except Exception as e:
        logger.error(f"获取章节内容接口错误: {e}")
        raise HTTPException(status_code=500, detail=f"获取内容失败: {str(e)}")


# 启动命令说明
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "app:app",
        host=config.API_HOST,
        port=config.API_PORT,
        reload=True
    )


# 皖ICP备18008684号-2 《https://beian.miit.gov.cn/》 uvicorn app:app --host 0.0.0.0 --port 8000 playwright install
